<template>
	<div class="point-box">
		<Table :columns="tableColumns" :data="[data]" />
	</div>
</template>
<script>
import { TableColumns } from '@/components/TableContainer'
import { rebateRender } from './config'
import Table from '@/components/Table'
export default {
	components: {
		Table
	},
	props: {
		name: {
			type: String,
			default: ''
		},
		columns: {
			type: Array,
			default: () => []
		},
		customColumns: {
			type: Object,
			default: () => ({})
		},
		value: {
			type: Object,
			default: () => ({})
		},
		subLabel: {
			type: String,
			default: '团队返点'
		},
		maxValueRange: {
			type: Object,
			default: () => ({})
		},
		isEdit: {
			type: Boolean,
			default: false
		}
	},
	data() {
		const rule = {
			validator: (rule, val, callback) => {
				const field = rule['field']
				if (!val && val !== 0) {
					return callback(new Error(`请输入比例`))
				}
				const path = field.split('.') || []
				const max = this.maxValueRange[path[1]]
				
				if (max && (val > max)) {
					return callback(new Error(`比例范围0-${max}`))
				}

				if (max === 0 && val > max) {
					return callback(new Error(`比例不能大于${max}`))
				}

				return callback()
			},
			trigger: 'blur'
		}

		const editPointRender = ({ row, column }) => {
			const prop = column.property
			const val = this.value[prop]
			return (
				<el-form-item
					rules={rule}
					prop={`${this.name}.${prop}`}
				>
					<div class='edit-number'>
						<el-input-number
							precision={3}
							controls={false}
							min={0}
							placeholder={val?.toString?.() || '0.000'}
							value={this.value[prop]}
							onChange={(newVal) =>
								this.handleItemChange(prop, newVal)
							}
						/>
						<span>&nbsp;%</span>
					</div>
				</el-form-item>
			)
		}

		const header = (label, subLabel) => {
			return (
				<div>
					{label}
					<p>
						{subLabel || this.subLabel}
					</p>
				</div>
			)
		}

		const tableColumns = this.columns.map((col) => {
			return TableColumns.edit({
					...col,
					header: (arg) => header(col.label),
					editRender: editPointRender,
					customRender: rebateRender,
					minWidth: '120px',
					width: '120px'
				})
		})

		return {
			// eslint-disable-next-line vue/no-reserved-keys
			tableColumns
		}
	},
	computed: {
		data() {
			return {
				isEdit: this.isEdit,
				...this.value
			}
		}
	},
	methods: {
		async queryLimit() {
			const res = await this.$api.rebateRateQueryLimit()
			if (res.code === 200) {
				this.maxRebateLimit = res.data
			}
		},
		handleItemChange(prop, newVal) {
			this.$emit(
				'input',
				Object.assign({}, this.value, {
					[prop]: newVal
				})
			)
		}
	}
}
</script>

<style scoped>

::v-deep .edit-number .el-input-number {
	width: auto;
}
::v-deep .edit-number .el-input input {
	width: 80px;
}

.point-box{
	overflow: auto;
	display: inline-block;
}
</style>
